package com.sx.wechat.controller;

import com.sx.core.utils.PropertyUtils;
import com.sx.core.utils.SpringUtils;
import com.sx.core.vo.JsonReaderResponse;
import com.sx.core.vo.Params;
import com.sx.wechat.command.cmd.Command;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by lihao on 2018/3/21.
 */
@RestController
@RequestMapping("api")
public class ApiController {
    protected final transient Log logger = LogFactory.getLog(getClass());
    private String fileLocation= PropertyUtils.getProperty("file.location");
    private String fileUrl= PropertyUtils.getProperty("file.url");
    @RequestMapping("{prefix}/{cmd}")
    public Object api(@PathVariable String prefix, @PathVariable String cmd, HttpServletRequest request, HttpServletResponse response, Model model){
        Command command = (Command) SpringUtils.getBean(cmd);
        if(command==null){
            return ResponseEntity.notFound().build();
        }
        return command.execute(prefix,request,response,model,null);
    }


    @RequestMapping("upload_file")
    public JsonReaderResponse upload_file(HttpServletRequest request, HttpServletResponse response, Model model, @RequestParam("file")MultipartFile file){
        String url=null;
        if(file!=null){
            String fileName = file.getOriginalFilename();
            File fileOnServer = null;
            String static_dir="attach";
            String dir_str = FilenameUtils.normalize(fileLocation + File.separator+static_dir+File.separator);
            File dir=new File(dir_str);
            if(!dir.exists()){
                dir.mkdirs();
            }
            String ext=FilenameUtils.getExtension(fileName);
            fileName= UUID.randomUUID().toString()+"."+ext;
            fileOnServer=new File(dir,fileName);
            try {
                byte[] bytes = file.getBytes();
                FileUtils.writeByteArrayToFile(fileOnServer,bytes);
            } catch (IOException e) {
                logger.error(e);
            }
            url=fileUrl.endsWith("/")?(fileUrl+static_dir+"/"+fileName):fileUrl+"/"+static_dir+"/"+fileName;
            return new JsonReaderResponse().addExtra(new Params().p("url",url));
        }
        return new JsonReaderResponse("上传失败",101);
    }


    @ExceptionHandler
    public Object exp(HttpServletRequest request, HttpServletResponse response, Exception ex) {
        logger.error("execute "+getClass()+"",ex);
        if(ex instanceof MissingServletRequestParameterException){
            MissingServletRequestParameterException parameterException=(MissingServletRequestParameterException)ex;
            return new JsonReaderResponse("缺少必要参数:"+parameterException.getParameterName(),10005);
        }else if(ex instanceof MethodArgumentTypeMismatchException){
            MethodArgumentTypeMismatchException typeMismatchException=(MethodArgumentTypeMismatchException)ex;
            return new JsonReaderResponse("参数["+typeMismatchException.getName()+"]类型错误，需要:"+typeMismatchException.getParameter().getNestedGenericParameterType().getTypeName(),10006);
        }
        return new JsonReaderResponse("执行错误",50001);

    }


}
